const nodemailer = require('nodemailer');
const logger = require('./logger');

/**
 * 发件箱配置
 */
const transporter = nodemailer.createTransport({
  host: process.env.MAILER_HOST,
  port: process.env.MAILER_PORT,
  secure: process.env.MAILER_SECURE,
  auth: {
    user: process.env.MAILER_USER,
    pass: process.env.MAILER_PASS,
  },
});

/**
 * 发送邮件
 * @param email
 * @param subject
 * @param html
 * @returns {Promise<void>}
 */
const sendMail = async (email, subject, html) => {
  try {
    await transporter.sendMail({
      from: process.env.MAILER_USER,
      to: email,
      subject,
      html,
    });
  } catch (error) {
    logger.error('邮件发送失败：', error);
  }
};

/**
 * 发送注册用户邮件
 * @param email
 * @returns {Promise<void>}
 */
const sendRegisterMail = async (nickname, email) => {
  const subject = `「${process.env.APPNAME}」的注册成功通知`;
  const html = `
    您好，<span style="color: red">${nickname}。</span><br><br>
    恭喜，您已成功注册会员！<br><br>
    请访问<a href="https://clwy.cn">「长乐未央」</a>官网，了解更多。<br><br>
    ━━━━━━━━━━━━━━━━<br>
    长乐未央
  `;
  await sendMail(email, subject, html);
};

module.exports = {
  sendMail,
  sendRegisterMail,
};
